package cn.zxcoder.controller.goods;

import cn.zxcoder.Tools.BarcodeUtils;
import cn.zxcoder.entity.Res;
import cn.zxcoder.entity.SystemManage.Dept;
import cn.zxcoder.entity.annotation.MyLog;
import cn.zxcoder.entity.goods.Product;
import cn.zxcoder.entity.goods.Repertory;
import cn.zxcoder.service.IDeptService;
import cn.zxcoder.service.IProductService;
import cn.zxcoder.service.IRepertoryService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zx
 * @since 2023-05-21
 */
@RestController
@RequestMapping("/api/Repertory")
@Slf4j
@Api(tags = "实现库存的CRUD和扫码")
public class RepertoryController {

    @Autowired
    IRepertoryService iRepertoryServiceIml;

    @Autowired
    IProductService iProductServiceIml;

    @Autowired
    IDeptService iDeptServiceIml;

    @ApiOperation("获取库存信息")
    @PostMapping("/list")
    @Transactional(readOnly = true)
    public Res getInventory(@RequestParam String page, @RequestParam String limit, @RequestParam String productName, @RequestParam String productCode) {

        Page<Repertory> repertoryPage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<Repertory> wrapper = new QueryWrapper<>();
        if (productCode.equals("")) {
            wrapper.like("name", productName);
        } else {
            wrapper.eq("code", productCode);
        }
        Page<Repertory> page1 = iRepertoryServiceIml.page(repertoryPage, wrapper);
        if (page1.getRecords().size() == 0) {
            return new Res(false, JSON.toJSONString(page1), "库存空空如也");
        }
        return new Res(true, JSON.toJSONString(page1), "成功获取了库存信息");

    }

    @ApiOperation("保存库存信息")
    @Transactional
    @PostMapping("/save")

    public Res saveInventory(@RequestParam boolean issave, @RequestParam String id, @RequestParam String name,@RequestParam String username,
                       @RequestParam String inventory, @RequestParam String unit, @RequestParam String location,@RequestParam String alarmValue) {
        if (issave) {
            Repertory repertory = new Repertory();
            repertory.setName(name);
            repertory.setInventory(Integer.parseInt(inventory));
            repertory.setInventorySum(0);
            repertory.setInventoryRemove(0);
            repertory.setUnit(Integer.parseInt(unit));
            repertory.setlocation(location);
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("goodsName", name);

            Product product = iProductServiceIml.getOne(productQueryWrapper);
            if (product == null) {
                return new Res(false, null, "库存中没有这样的商品哦");
            }
            Integer code = product.getId();
            repertory.setCode("" + code);
            repertory.setAlarmValue(Integer.parseInt(alarmValue));
            repertory.setAlarm(Integer.parseInt(inventory) > Integer.parseInt(alarmValue) ? 0 : 1);
            repertory.setType("饮料");
            repertory.setImg("src/assets/img");
            repertory.setStatusCode(0);
            repertory.setaddTime(new Date());
            repertory.setaddUser(username);
            boolean save = iRepertoryServiceIml.save(repertory);

            //设置条形码url
            QueryWrapper<Repertory> repertoryQueryWrapper = new QueryWrapper<>();
            repertoryQueryWrapper.eq("name", name);
            Repertory repertory1 = iRepertoryServiceIml.getOne(repertoryQueryWrapper);

            Long id1 = repertory1.getId();
            String goodsName = product.getGoodsName();

            String msg = id1 + ":"+code;
            String path = String.format("src/main/java/cn/zxcoder/codeImg/barcode%s.png", id1);
            repertory.setImgUrl(path);

            //生成条形码
            BarcodeUtils.generateFile(msg, path);
            return new Res(save, null, save ? "保存库存信息成功" : "保存库存信息失败");

        } else {
            UpdateWrapper<Repertory> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", Integer.parseInt(id));
            wrapper.set("name", name);
            QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("goodsName", name);
            wrapper.set("code", iProductServiceIml.getOne(productQueryWrapper).getId());
            wrapper.set("inventory", Integer.parseInt(inventory));
            wrapper.set("location", location);
            wrapper.set("alarm_value", alarmValue);

            QueryWrapper<Product> productQueryWrapper2 = new QueryWrapper<>();
            productQueryWrapper2.eq("goodsName", name);
            Product product = iProductServiceIml.getOne(productQueryWrapper2);
            Integer code = product.getId();

            String msg = id +":"+ code;
            String path = String.format("src/main/java/cn/zxcoder/codeImg/barcode%s.png", id);
            BarcodeUtils.generateFile(msg, path);//生成对应的条形码

            boolean update = iRepertoryServiceIml.update(wrapper);
            return new Res(update, null, update ? "编辑库存信息成功" : "编辑库存信息失败");
        }

    }


    @ApiOperation("删除支付配置")
    @DeleteMapping("/delete/{id}")
    @Transactional

    public Res deleteInventory(@PathVariable String id) {
        boolean b = iRepertoryServiceIml.removeById(Integer.parseInt(id));
        return new Res(b, null, b ? "删除库存成功" : "删除库存信息失败");
    }

    @ApiOperation("获取部门信息")
    @GetMapping("/dept")
    @Transactional

    public Res getDept() {
        List<Dept> list = iDeptServiceIml.list();
        System.out.println(list);
        return new Res(true, JSON.toJSONString(list),"获取部门信息成功");
    }


    @ApiOperation("获取扫描信息")
    @PostMapping("/show")
    @Transactional
    public Res getScan(@RequestParam String codeParam) {
        String[] split = codeParam.split(":");
        String id = split[0];
//        String code = split[1];
//        String name = split[2];
        if (id.equals("")) {
            return new Res(false, null, "获取失败，条形码有误");
        }
        Repertory repertory = iRepertoryServiceIml.getById(Integer.parseInt(id));
        return new Res(repertory!=null, JSON.toJSONString(repertory),repertory==null?"没在库存找到相应的商品":"获取扫描的部门信息成功");
    }

    @ApiOperation("入库操作")
    @PostMapping("/in")
    @MyLog(operation = "入库操作")
    @Transactional
//    @RequestParam String id, @RequestParam String value, @RequestParam String name
    public Res In(HttpServletRequest request,@RequestParam List<Integer> ids, @RequestParam List<String> values,
                  @RequestParam List<String> names) {//记录日志


        int size = ids.size();
        int count = 0;

        for (int i = 0; i < size; i++) {
            Integer id = ids.get(i);
            String value = values.get(i);
            String name = names.get(i);
            UpdateWrapper<Repertory> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            Repertory repertory = iRepertoryServiceIml.getById(id);
            Integer inventory = repertory.getInventory();
            Integer inventorySum = repertory.getInventorySum();
            String username = request.getHeader("username");

            inventory += Integer.parseInt(value);
            inventorySum += Integer.parseInt(value);

            wrapper.set("inventory", inventory);
            wrapper.set("inventory_Sum", inventorySum);
            wrapper.set("editUser", username);
            wrapper.set("editTime", new Date());

            boolean update = iRepertoryServiceIml.update(wrapper);

            if (update) {//记录日志
                log.info("操作编号:" + id);
                log.info("操作用户:" + username);
                log.info("操作时间:" + new Date());
                log.info("操作商品名:"+name);
                log.info("操作类型:入库");
                log.info("入库的数量:"+value);
                count++;
            }
        }
        return new Res(count==size, null, count==size ? "入库成功" : "入库失败");


    }

    @ApiOperation("出库操作")
    @PostMapping("/out")
    @MyLog(operation = "出库操作")
    @Transactional

    public Res Out(HttpServletRequest request, @RequestParam List<Integer> ids, @RequestParam List<String> values,
                   @RequestParam List<String> names) {//记录日志



        int size = ids.size();
        int count = 0;

        for (int i = 0; i < size; i++) {

            Integer id = ids.get(i);
            String value = values.get(i);
            String name = names.get(i);

            UpdateWrapper<Repertory> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", id);
            Repertory repertory = iRepertoryServiceIml.getById(id);
            Integer inventory = repertory.getInventory();
            Integer inventoryRemove = repertory.getInventoryRemove();
            String username = request.getHeader("username");

            inventory -= Integer.parseInt(value);
            inventoryRemove += Integer.parseInt(value);
            if (inventory < 0) {
                return new Res(false, null, "现库存总量不足");
            }

            wrapper.set("inventory", inventory);
            wrapper.set("inventory_Remove", inventoryRemove);
            wrapper.set("editUser", username);
            wrapper.set("editTime", new Date());

            boolean update = iRepertoryServiceIml.update(wrapper);


            if (update) {//记录日志
                log.info("操作编号:" + id);
                log.info("操作用户:" + username);
                log.info("操作时间:" + new Date());
                log.info("操作商品名:"+name);
                log.info("操作类型:出库");
                log.info("出库的数量:"+value);
                count++;
            }
        }


        return new Res(count==size, null, count==size ? "出库成功" : "出库失败");
    }

    @Transactional
    @ApiOperation("上传excel数据到数据库")
    @PostMapping("/up")

    public Res upData(HttpServletRequest request,@RequestParam String name,@RequestParam String location,@RequestParam String inventorySum,
                      @RequestParam String inventoryRemove,@RequestParam String inventory,@RequestParam String alarmValue) {


//        boolean save = iRepertoryServiceIml.saveBatch(listData);
//        listData.forEach(i->{i.setaddTime(new Date());
//            i.setaddUser(request.getHeader("username"));});
        Repertory repertory = new Repertory();
        repertory.setName(name);
        repertory.setlocation(location);
        repertory.setInventorySum(Integer.parseInt(inventorySum));
        repertory.setInventoryRemove(Integer.parseInt(inventoryRemove));
        repertory.setInventory(Integer.parseInt(inventory));
        repertory.setAlarmValue(Integer.parseInt(alarmValue));
        repertory.setaddUser(request.getHeader("username"));
        repertory.setaddTime(new Date());

        boolean save = iRepertoryServiceIml.save(repertory);
        return new Res(save, null, save ? "上传至数据库成功" : "上传数据库失败");
    }

    @ApiOperation("下载数据文件")
    @PostMapping("/down")
    @Transactional
    public Res downData(@RequestParam String codeParam) {

        return new Res(true, null,"获取扫描的部门信息成功");
    }


}
